<?php

namespace Core\http;
class  Response
{
    /**
     * @var \Swoole\Http\Response
     * 当该文件中有用到response的方法和属性的时候，没有提示，添加上上面的这句话就会有提示了。
     */
    protected $swooleReponse;
    protected $body;


    public function __construct($swooleReponse)
    {
        $this->swooleReponse = $swooleReponse;
        $this->setHeader('Content-Type','text/plain;charset=UTF-8');
    }

    public static function init(\Swoole\Http\Response $response): Response
    {
        return new self($response);
    }

    public function getBody()
    {
        return $this->body;
    }

    public function setBody($body)
    {
        $this->body = $body;
    }



    public function setHeader($key,$value)
    {
        $this->swooleReponse->header($key,$value);
    }

    public function redirect($url,$code=301)
    {
        $this->swooleReponse->status($code);
        $this->setHeader('Location',$url);
    }

    public function end()
    {
        $ret = $this->getBody();
        switch (gettype($ret)) {
            case 'array':
                $this->swooleReponse->header("Content-type","application/json;charset=utf-8");
                $this->swooleReponse->write(json_encode($ret, true));
                break;
            case 'string':
                $this->swooleReponse->write($ret);
                break;
        }


        $this->swooleReponse->end();
    }


}
